package com.ibeetl.admin.console.service;

import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ibeetl.admin.console.dao.AvailableCoinDao;
import com.ibeetl.admin.console.dao.AvailableScoreDao;
import com.ibeetl.admin.console.dao.BackChargeDao;
import com.ibeetl.admin.console.dao.CoinDetailDao;
import com.ibeetl.admin.console.dao.CoinTemplateDao;
import com.ibeetl.admin.console.dao.LeaveMsgConsoleDao;
import com.ibeetl.admin.console.dao.PayOrderConsoleDao;
import com.ibeetl.admin.console.dao.RechargeConsoleDao;
import com.ibeetl.admin.console.dao.ScoreDetailDao;
import com.ibeetl.admin.console.dao.ScoreTemplateDao;
import com.ibeetl.admin.console.dao.UserConsoleDao;
import com.ibeetl.admin.console.dao.UserExtendDao;
import com.ibeetl.admin.console.exception.DeletedException;
import com.ibeetl.admin.console.exception.NoResourceException;
import com.ibeetl.admin.console.web.dto.LeaveMsgExcelExportData;
import com.ibeetl.admin.console.web.dto.PayOrderExcelExportData;
import com.ibeetl.admin.console.web.dto.RechargeExcelExportData;
import com.ibeetl.admin.console.web.dto.UserExcelExportData;
import com.ibeetl.admin.console.web.query.UserRoleQuery;
import com.ibeetl.admin.core.conf.PasswordConfig.PasswordEncryptService;
import com.ibeetl.admin.core.entity.AvailableCoin;
import com.ibeetl.admin.core.entity.AvailableScore;
import com.ibeetl.admin.core.entity.BackCharge;
import com.ibeetl.admin.core.entity.CoinDetail;
import com.ibeetl.admin.core.entity.CoinTemplate;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.CoreUserRole;
import com.ibeetl.admin.core.entity.LeaveMsg;
import com.ibeetl.admin.core.entity.PayOrder;
import com.ibeetl.admin.core.entity.Recharge;
import com.ibeetl.admin.core.entity.ScoreDetail;
import com.ibeetl.admin.core.entity.ScoreTemplate;
import com.ibeetl.admin.core.entity.UserExtend;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.rbac.tree.OrgItem;
import com.ibeetl.admin.core.service.BaseService;
import com.ibeetl.admin.core.service.CoreDictService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.enums.CoreDictType;
import com.ibeetl.admin.core.util.enums.DelFlagEnum;
import com.ibeetl.admin.core.util.enums.GeneralStateEnum;

@Service
@Transactional
public class RechargeConsoleService extends BaseService<Recharge> {

	@Autowired
	RechargeConsoleDao rechargeDao;
	
	@Autowired
	ScoreTemplateDao scoreTemplateDao;
	
	@Autowired
	CoinTemplateDao coinTemplateDao;
	
	@Autowired
	AvailableScoreDao availableScoreDao;
	
	@Autowired
	ScoreDetailDao scoreDetailDao;
	
	@Autowired
	UserExtendDao userExtendDao;
	
	@Autowired
	AvailableCoinDao availableCoinDao;
	
	@Autowired
	CoinDetailDao coinDetailDao;
	
	@Autowired
	BackChargeDao backChargeDao;
	
	@Autowired
    FileService fileService;

	@Autowired
	PasswordEncryptService passwordEncryptService;
	@Autowired
	CoreDictService dictService;

	
	@Autowired
	CorePlatformService platformService;
	/**
	 * 根据条件查询
	 *
	 * @param query
	 */
	public void queryByCondtion(PageQuery<Recharge> query) {
		PageQuery<Recharge> ret = rechargeDao.queryByCondtion(query);
		queryListAfter(ret.getList());
	}


	/**
	 * 根据订单号查询一条数据
	 *
	 * @param orderNo
	 */
	public Recharge queryRechargeById(String openId) {
		return rechargeDao.queryById(openId);
	}

	/**
	 * 删除一条订单
	 *
	 * @param orderNo
	 *
	 */
	public int doingRecharge(Recharge recharge) {
		
		if(recharge==null) {
			throw new NoResourceException("充值信息不存在!");
		}
		
		//元置换为分
		recharge.setScore(recharge.getScore()*100);
		
		String orderNo= UUID.randomUUID().toString().replace("-","");
		CoreUser currentUser = platformService.getCurrentUser();
		String currentUserCode = currentUser.getCode();
		String strShareId = recharge.getShareId();
		String strPshareId = recharge.getPshareId();
		Date dUserChargeTime = recharge.getUserChargeTime();
		int iUserChargeAmount = recharge.getUserChargeAmount();
		iUserChargeAmount = iUserChargeAmount*100;
				
		ScoreTemplate scoreTemplate = new ScoreTemplate();
		scoreTemplate.setType("5");
		double dScoreRate = 0;
		int iScoreLevel = 0;
		int iScoreValidityPeriod = 0;
		Date now = new Date(); 
		Calendar calendar = Calendar.getInstance();

		
		ScoreTemplate scoreTemplateTmp = scoreTemplateDao.queryByCondtion(scoreTemplate);
		if(scoreTemplateTmp!=null) {
			dScoreRate = scoreTemplateTmp.getRate();
			iScoreLevel = scoreTemplateTmp.getLevel();
			iScoreValidityPeriod = scoreTemplateTmp.getValidityPeriod();
		}else {
			throw new NoResourceException("充值模板5没找到!");
		}
		
		AvailableScore availableScore = new AvailableScore();
		availableScore.setOpenId(recharge.getOpenId());
		availableScore.setScore(Math.round(recharge.getScore()*dScoreRate/100));
		availableScore.setType("5");
		calendar.add(Calendar.MONTH, iScoreValidityPeriod);
		availableScore.setExpireTime(calendar.getTime());
		availableScore.setLevel(iScoreLevel);
		availableScore.setCreator(currentUserCode);
		availableScore.setCreateTime(now);
		availableScore.setNote("后台充值");
		availableScoreDao.insert(availableScore);

		ScoreDetail scoreDetail = new ScoreDetail();
		scoreDetail.setOpenId(recharge.getOpenId());
		scoreDetail.setScore(Math.round(recharge.getScore()*dScoreRate/100));
		scoreDetail.setType("5");
		scoreDetail.setExpireTime(calendar.getTime());
		scoreDetail.setCreator(currentUserCode);
		scoreDetail.setCreateTime(now);
		scoreDetail.setNote("后台充值");
		scoreDetailDao.insert(scoreDetail);
		
		UserExtend userExtend = userExtendDao.queryById(recharge.getOpenId());
		
		if(userExtend!=null) {
			userExtend.setScore(userExtend.getScore()+Math.round(recharge.getScore()*dScoreRate/100));
			userExtendDao.updateById(userExtend);
		}else {
			throw new NoResourceException("用户扩展信息没找到!");
		}
		
		if(recharge.getGiveScore()>0) {
			
			ScoreTemplate scoreTemplateGive = new ScoreTemplate();
			scoreTemplateGive.setType("4");
			double dScoreRateGive = 0;
			int iScoreLevelGive = 0;
			int iScoreValidityPeriodGive = 0;
			Calendar calendarGive = Calendar.getInstance();
			
			ScoreTemplate scoreTemplateTmpGive = scoreTemplateDao.queryByCondtion(scoreTemplate);
			if(scoreTemplateTmpGive!=null) {
				dScoreRateGive = scoreTemplateTmpGive.getRate();
				iScoreLevelGive = scoreTemplateTmpGive.getLevel();
				iScoreValidityPeriodGive = scoreTemplateTmpGive.getValidityPeriod();
			}else {
				throw new NoResourceException("充值模板4没找到!");
			}
			
			AvailableScore availableScoreGive = new AvailableScore();
			availableScoreGive.setOpenId(recharge.getOpenId());
			availableScoreGive.setScore(Long.parseLong(recharge.getGiveScore()+""));
			availableScoreGive.setType("4");
			calendarGive.add(Calendar.MONTH, iScoreValidityPeriodGive);
			availableScoreGive.setExpireTime(calendarGive.getTime());
			availableScoreGive.setLevel(iScoreLevelGive);
			availableScoreGive.setCreator(currentUserCode);
			availableScoreGive.setCreateTime(now);
			availableScoreGive.setNote("后台充值赠送");
			availableScoreDao.insert(availableScoreGive);
			
			ScoreDetail scoreDetailGive = new ScoreDetail();
			scoreDetailGive.setOpenId(recharge.getOpenId());
			scoreDetailGive.setScore(Long.parseLong(recharge.getGiveScore()+""));
			scoreDetailGive.setType("4");
			scoreDetailGive.setExpireTime(calendarGive.getTime());
			scoreDetailGive.setCreator(currentUserCode);
			scoreDetailGive.setCreateTime(now);
			scoreDetailGive.setNote("后台充值");
			scoreDetailDao.insert(scoreDetailGive);
			
			UserExtend userExtendGive = userExtendDao.queryById(recharge.getOpenId());
			
			if(userExtendGive!=null) {
				userExtendGive.setScore(userExtendGive.getScore()+recharge.getGiveScore());
				userExtendDao.updateById(userExtendGive);
			}else {
				throw new NoResourceException("用户扩展信息没找到!");
			}
			
		}
		
		if((strShareId!=null)&&!(strShareId.equals(""))) {
			CoinTemplate coinTemplate = new CoinTemplate();
			coinTemplate.setType("A");
			double dCoinRate = 0;
			int iCoinValidityPeriod = 0;
			Calendar calendarCoin = Calendar.getInstance();
			
			CoinTemplate coinTemplateTmp = coinTemplateDao.queryByCondtion(coinTemplate);
			if(coinTemplateTmp!=null) {
				dCoinRate = coinTemplateTmp.getRate();
				iCoinValidityPeriod = coinTemplateTmp.getValidityPeriod();
			}else {
				throw new NoResourceException("充值模板A没找到!");
			}
			
			AvailableCoin availableCoin = new AvailableCoin();
			availableCoin.setOpenId(strShareId);
			availableCoin.setScore(Math.round(recharge.getScore()*dCoinRate/100));
			availableCoin.setType("A");
			calendarCoin.add(Calendar.MONTH, iCoinValidityPeriod);
			availableCoin.setExpireTime(calendarCoin.getTime());
			availableCoin.setCreator(currentUserCode);
			availableCoin.setCreateTime(now);
			availableCoin.setNote("直荐云币奖励");
			availableCoinDao.insert(availableCoin);
			
			CoinDetail coinDetail = new CoinDetail();
			coinDetail.setOpenId(strShareId);
			coinDetail.setBeShareId(recharge.getOpenId());
			coinDetail.setScore(Math.round(recharge.getScore()*dCoinRate/100));
			coinDetail.setType("A");
			coinDetail.setExpireTime(calendarCoin.getTime());
			coinDetail.setOrderNo(orderNo);
			coinDetail.setCreator(currentUserCode);
			coinDetail.setCreateTime(now);
			//coinDetail.setNote("直荐云币奖励");
			coinDetailDao.insert(coinDetail);
			
		}
		
		if((strPshareId!=null)&&!(strPshareId.equals(""))) {
			CoinTemplate coinTemplate = new CoinTemplate();
			coinTemplate.setType("B");
			double dCoinRate = 0;
			int iCoinValidityPeriod = 0;
			Calendar calendarCoin = Calendar.getInstance();
			
			CoinTemplate coinTemplateTmp = coinTemplateDao.queryByCondtion(coinTemplate);
			if(coinTemplateTmp!=null) {
				dCoinRate = coinTemplateTmp.getRate();
				iCoinValidityPeriod = coinTemplateTmp.getValidityPeriod();
			}else {
				throw new NoResourceException("充值模板B没找到!");
			}
			
			AvailableCoin availableCoin = new AvailableCoin();
			availableCoin.setOpenId(strPshareId);
			availableCoin.setScore(Math.round(recharge.getScore()*dCoinRate/100));
			availableCoin.setType("B");
			calendarCoin.add(Calendar.MONTH, iCoinValidityPeriod);
			availableCoin.setExpireTime(calendarCoin.getTime());
			availableCoin.setCreator(currentUserCode);
			availableCoin.setCreateTime(now);
			availableCoin.setNote("转荐云币奖励");
			availableCoinDao.insert(availableCoin);
			
			CoinDetail coinDetail = new CoinDetail();
			coinDetail.setOpenId(strPshareId);
			coinDetail.setBeShareId(recharge.getOpenId());
			coinDetail.setScore(Math.round(recharge.getScore()*dCoinRate/100));
			coinDetail.setType("B");
			coinDetail.setOrderNo(orderNo);
			coinDetail.setExpireTime(calendarCoin.getTime());
			coinDetail.setCreator(currentUserCode);
			coinDetail.setCreateTime(now);
			//coinDetail.setNote("转荐云币奖励");
			coinDetailDao.insert(coinDetail);
			
		}
		
		BackCharge backCharge = new BackCharge();
		backCharge.setOpenId(recharge.getOpenId());
		backCharge.setAmount(new Long(recharge.getScore()).intValue());
		backCharge.setScore(new Double(recharge.getScore()*dScoreRate/100).intValue());
		backCharge.setGiftScore(recharge.getGiveScore());
		backCharge.setCreator(currentUserCode);
		backCharge.setCreateTime(now);
		backCharge.setOrderNo(orderNo);
		backCharge.setUserChargeTime(dUserChargeTime);
		backCharge.setUserChargeAmount(iUserChargeAmount);
		backChargeDao.insert(backCharge);

		return 1;
		//rechargeDao.delPayOrderById(openId);
	}

	public List<RechargeExcelExportData> queryExcel(PageQuery<Recharge> query) {
		PageQuery<Recharge> ret = rechargeDao.queryByCondtion(query);
		List<Recharge> list = ret.getList();
		OrgItem orgRoot = platformService.buildOrg();
		List<RechargeExcelExportData> items = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		for(Recharge recharge:list) {
			RechargeExcelExportData rechargeItem = new RechargeExcelExportData();
			rechargeItem.setOpenId(recharge.getOpenId());
			rechargeItem.setNickName(recharge.getNickName());
			
			rechargeItem.setSex(recharge.getSex());
			rechargeItem.setScore(recharge.getScore());
			rechargeItem.setShareId(recharge.getShareId());
			
			rechargeItem.setPshareId(recharge.getPshareId());
			rechargeItem.setCreateTime(sdf.format(recharge.getCreateTime()));
			rechargeItem.setLastLogin(sdf.format(recharge.getLastLogin()));
			
			items.add(rechargeItem);
			
		}
		return items;
		
	}
}
